package org.androidpn.net;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolAgent {

	private static final String TAG = ThreadPoolAgent.class.getSimpleName();
	// 共用线程池
	private static ExecutorService mCachedThreadPool;
	private static ExecutorService mSingleThreadPool;

	/**
	 * 开启线程池
	 */
	public static void openThreadPool() {
		// 先释放线程池
		closeThreadPool();

		// 创建线程池
		mCachedThreadPool = Executors.newCachedThreadPool();
		mSingleThreadPool = Executors.newSingleThreadExecutor();
	}

	/**
	 * 执行异步任务
	 * 
	 * @param task
	 *            耗时任务
	 */
	public static void executeAsynTask(Runnable task) {
		// 判断是否被关闭
		if (mCachedThreadPool == null || mCachedThreadPool.isShutdown()) {
			mCachedThreadPool = Executors.newCachedThreadPool();
		}
		mCachedThreadPool.execute(task);
	}

	/**
	 * 顺序执行任务
	 */
	public static void executeOrderTask(Runnable task) {
		// 判断是否被关闭
		if (mSingleThreadPool == null || mSingleThreadPool.isShutdown()) {
			mSingleThreadPool = Executors.newSingleThreadExecutor();
		}
		mSingleThreadPool.execute(task);
	}

	/**
	 * 关闭线程池
	 */
	public static void closeThreadPool() {
		if (mCachedThreadPool != null && !mCachedThreadPool.isShutdown()) {
			mCachedThreadPool.shutdownNow();
			mCachedThreadPool = null;
		}
		if (mSingleThreadPool != null && !mSingleThreadPool.isShutdown()) {
			mSingleThreadPool.shutdownNow();
			mSingleThreadPool = null;
		}
	}

}
